<template>
	<view class="page-body">
		<!-- 页面内容开始 -->

		<!-- 表格搜索组件开始 -->
		<vk-data-table-query
			v-model="queryForm1.formData"
			:columns="queryForm1.columns"
			size="mini"
			:main-columns="['is_fx','vip_lv','fx_lv','nickname','mobile','_id','inviter_uid','comment','vip_code']"
			@search="search"
		></vk-data-table-query>
		<!-- 表格搜索组件结束 -->

		<!-- 自定义按钮区域开始 -->
		<!-- <view>
			<el-button type="success" size="small" icon="el-icon-circle-plus-outline" @click="applyQRcode('888888')">显示平台推广码</el-button>
		</view> -->
		<!-- 自定义按钮区域结束 -->

		<!-- 表格组件开始 -->
		<vk-data-table
			ref="table1"
			:action="table1.action"
			:columns="table1.columns"
			:query-form-param="queryForm1"
			:right-btns="['detail_auto','update','more']"
			:right-btns-more="table1.rightBtnsMore"
			:selection="false"
			:row-no="true"
			:pagination="true"
			:custom-right-btns="table1.customRightBtns"
			size="mini"
			@update="updateBtn"
			@current-change="currentChange"
			@selection-change="selectionChange"
		>
			<template v-slot:btn1="{ row, column, index }">
				<view>
					<view v-if="row.inviter_uid && row.inviter_uid[0]">
						<el-button size="mini" type="text" @click="querySj(row.inviter_uid[0])">查看上级</el-button>
					</view>
					<view v-if="row._id">
						<el-button size="mini" type="text" @click="queryXj(row._id)">查看下级</el-button>
					</view>
				</view>
			</template>
		</vk-data-table>
		<!-- 表格组件结束 -->

		<!-- 添加或编辑的弹窗开始 -->
		<vk-data-dialog
			v-model="form1.props.show"
			:title="form1.props.title"
			width="500px"
			mode="form"
			:close-on-click-modal="false"
		>
			<vk-data-form
				v-model="form1.data"
				:rules="form1.props.rules"
				:action="form1.props.action"
				:form-type="form1.props.formType"
				:columns='form1.props.columns'
				label-width="100px"
				@success="form1.props.show = false;refresh();"
			>
			<!-- v-slot:rate 中的 rate 对应 columns中的 key, form对应 form1.data keyName 对应 columns中的 key -->
				<template v-slot:tags="{ form, keyName }">
					<view>
						<userTagscom v-model="form[keyName]" :userInfo="form"></userTagscom>
					</view>
				</template>
			</vk-data-form>
		</vk-data-dialog>
		<!-- 添加或编辑的弹窗结束 -->

		<userRecords v-model="formDatas.userRecords" @success="refresh"></userRecords>
		<examineSalesman v-model="formDatas.examineSalesman"></examineSalesman>
		<updateInviter v-model="formDatas.updateInviter" @success="refresh"></updateInviter>
		<userTags v-model="formDatas.userTags" @success="refresh"></userTags>
		<isServiceStaff v-model="formDatas.isServiceStaff"></isServiceStaff>
		<isVerifyStaff v-model="formDatas.isVerifyStaff"></isVerifyStaff>
		<applyqrcode v-model="formDatas.applyqrcode"></applyqrcode>
		<updateFxLv v-model="formDatas.updateFxLv"></updateFxLv>

		<!-- 余额 -->
		<balance v-model="formDatas.balance"></balance>
		<!-- 积分 -->
		<integral v-model="formDatas.integral"></integral>
		<!-- 余额转账 -->
		<balanceTransfer v-model="formDatas.balanceTransfer" @success="refresh"></balanceTransfer>

		<!-- 页面内容结束 -->
	</view>
</template>

<script>
	var that;													// 当前页面对象
	var vk = uni.vk;									// vk实例
	var originalForms = {};						// 表单初始化数据
	var statusData = [
		{ value:0, label:"正常", tagType: "success" },
		{ value:1, label:"禁用", tagType: "danger" },
	];
	var fxStatusData = [
		{ value:0, label:"等待审核", tagType: "danger" },
		{ value:1, label:"通过", tagType: "success" },
		{ value:2, label:"拒绝", tagType: "danger" },
		{ value:3, label:"冻结", tagType: "danger" },
		{ value:-1, label:"无", tagType: "info" },
	];
	var fxLvData = vk.getVuex("$user.mchInfo.fx.level_rule");
	var vipLvData = vk.getVuex("$user.mchInfo.vip_level_rule");

	import userRecords from './userRecords'
	import examineSalesman from './form/examineSalesman'
	import updateInviter from './form/updateInviter'
	import userTags from './form/userTags'
	import isServiceStaff from './form/isServiceStaff'
	import isVerifyStaff from './form/isVerifyStaff'
	import applyqrcode from './form/applyqrcode'
	import userTagscom from './form/userTagscom'
	import updateFxLv from './form/updateFxLv'


	import balance from './form/balance'
	import integral from './form/integral'
	import balanceTransfer from './form/balanceTransfer'


	export default {
		components:{
			userRecords,
			examineSalesman,
			updateInviter,
			userTags,
			isServiceStaff,
			isVerifyStaff,
			applyqrcode,
			userTagscom,
			updateFxLv,

			balance,
			integral,
			balanceTransfer
		},
		data() {
			// 页面数据变量
			return {
				// 页面是否请求中或加载中
				loading:false,
				// init请求返回的数据
				data:{

				},
				// 表格相关开始 -----------------------------------------------------------
				table1:{
					// 表格数据请求地址
					action:"admin/business/sys/user.getList",
					// 表格字段显示规则
					columns:[
						{ key:"btn1", title:"操作", type:"text", width:100 },
						{ key: "register_date", title: "账号信息", type: "group", width: 180, align:"left", sortable:"custom",
							columns:[
								{ key:"_id", title:"id", type:"text", width:300 },
								{ key:"username", title:"账号", type:"text", width:160, defaultValue:"未设置" },
								{ key:"register_date", title:"注册", type:"time", width:160, sortable:"custom" },
								{ key: "status" , title: "状态" , type: "tag" , width: 120, defaultValue:0,
									data:statusData
								},
								//{ key:"last_login_date", title:"登录", type:"dateDiff", width:160 },
							],
						},
						{ key:"avatar", title:"头像", type:"avatar", width:80, imageWidth:40, shape:"square" },
						{ key: "mobile", title: "用户信息", type: "group", width: 180, align:"left",
							columns:[
								{ key:"nickname", title:"昵称", type:"text", width:120 },
								{ key:"mobile", title:"手机", type:"text", width:120, defaultValue:"未绑定" },
								{ key:"wx_openid.mp-weixin", title:"wx_openid", type:"text", width:200},
								{ key:"vip_lv", title:"等级", type:"select", width:140, defaultValue:"-",
									data:()=>{
										return vipLvData;
									},
									props:{ value:'lv', label:'name', children:'children' },
									buttons: [
										{
											title: "修改",
											type: "text", // 文字形式按钮 可选：primary / success / warning / danger / info / text
											mode: "update", // 模式 可选：update（通用修改模式） / default（自定义模式）
											show: ["row"], // 在哪些场景显示按钮 多选：row（在行内显示） / detail（在详情页显示）
											click: (options) => {
												vk.callFunction({
													url: 'admin/business/sys/user.updateVipLv',
													data: options.formData,
													success: (data) => {
														// 通知组件操作成功（否则组件按钮会一直处于loading状态）
														options.success({
															msg: "修改成功"
														});
													}
												});
											}
										}
									]
								},
								{ key:"comment", title:"备注", type:"text", width:120, defaultValue:""  },
							],
						},
						{ key:"inviterUserInfo.avatar", title:"上级头像", type:"avatar", width:80, imageWidth:40, shape:"square" },
						{ key: "inviterUserInfo", title: "上级信息", type: "group", width: 180, align:"left",
							columns:[
								{ key:"inviterUserInfo.nickname", title:"昵称", type:"text", width:120, defaultValue:"",
									formatter: function(val, row, column, index) {
										let str = val;
										if (vk.pubfn.isNull(row.inviter_uid)){
											if (row.inviter_lock){
												str = "【归属系统】";
											} else {
												str = "【无推荐人】";
											}
										}
										return str;
									}
								},
								{ key:"inviterUserInfo.mobile", title:"手机", type:"text", width:120, defaultValue:"" },
								{ key:"inviterUserInfo.vip_lv", title:"会员", type:"select", width:140,
									data:()=>{
										return vipLvData;
									},
									props:{ value:'lv', label:'name', children:'children' }
								},
								{ key:"inviterUserInfo.fx.lv", title:"分销", type:"select", width:140, defaultValue:"-",
									data:()=>{
										return fxLvData;
									},
									props:{ value:'lv', label:'name', children:'children' }
								},
								//{ key:"inviterUserInfo.comment", title:"备注", type:"text", width:120, defaultValue:""  },
							],
						},

						{ key: "", title: "分销信息", type: "group", width: 220, align:"left",
							columns:[
								{ key:"fx.lv", title:"分销等级", type:"text", width:120, placeholder:"请选择等级", defaultValue:"-",
									formatter: (val, row, column, index) => {
										let str = `非分销员（用户）`;
										if (row.fx.is_fx) {
											let item = vk.pubfn.getListItem(fxLvData, "lv", val);
											str = item.name;
										}
										return str;
									},
									buttons: [
										{
											title: "修改",
											type: "text", // 文字形式按钮 可选：primary / success / warning / danger / info / text
											mode: "default", // 模式 可选：update（通用修改模式） / default（自定义模式）
											show: ["row"], // 在哪些场景显示按钮 多选：row（在行内显示） / detail（在详情页显示）
											// showRule:(row)=>{
											// 	return row.fx.is_fx;
											// },
											click: (options) => {
												vk.pubfn.openForm('updateFxLv',{ item: options.row })
											}
										}
									]
								},
								{ key:"my_invite_code", title:"Ta邀请码", type:"text", width:120, defaultValue:"无" },
								{ key:"invite_time", title:"受邀时间", type:"time", width:160, sortable:"custom" },
								{
									key:"fx.role", title:"身份类型", type:"tag", width:200,
									effect:"light", defaultValue:"-",
									data:[
										{ value:"-", label:"无" },
										{ value:"region", label:"区域代理" },
										{ value:"shareholder", label:"商城股东", tagType:"danger" }
									]
								}
							],
						},
						{ key: "account_per.my_payment", title: "累计消费", type: "money", width: 100, sortable:"custom", defaultValue:0 },
						{ key: "account_balance.balance", title: "余额账户", type: "group", width: 160, align:"left", sortable:"custom",
							columns:[
								{ key:"account_balance.balance", title:"余额", type:"money", width:120, sortable:"custom" },
								{ key:"account_balance.used", title:"使用", type:"money", width:120, sortable:"custom" },
								{ key:"account_balance.total", title:"累计", type:"money", width:120, sortable:"custom" },
							],
						},
						{ key: "account_reward.allow", title: "佣金账户", type: "group", width: 160, align:"left", sortable:"custom",
							columns:[
								{ key:"account_reward.wait", title:"在途", type:"money", width:120, sortable:"custom" },
								{ key:"account_reward.allow", title:"可提", type:"money", width:120, sortable:"custom" },
								{ key:"account_reward.total", title:"累计", type:"money", width:120, sortable:"custom" },
							],
						},
						{ key: "account_integral.balance", title: "积分账户", type: "group", width: 160, align:"left", sortable:"custom",
							columns:[
								{ key:"account_integral.balance", title:"余额", type:"number", width:120, sortable:"custom" },
								{ key:"account_integral.used", title:"使用", type:"number", width:120, sortable:"custom" },
								{ key:"account_integral.total", title:"累计", type:"number", width:120, sortable:"custom" },
							],
						},
						{ key: "fx.apply_time", title: "分销审核信息", type: "group", width: 250, align:"left", sortable:"custom",
							columns:[
								{ key: "fx.status" , title: "审核状态" , type: "tag" , width: 120 ,sortable:"custom", defaultValue:-1,
									data:fxStatusData
								},
								{ key:"fx.apply_time", title:"申请时间", type:"time", width:160, sortable:"custom" },
								{ key:"fx.apply_comment", title:"申请备注", type:"text", width:120 },
							],
						},
						{ key: "vip_lv", title: "会员详细信息", type: "group", width: 250, align:"left", sortable:"custom",
							columns:[
								{ key:"vip_lv", title:"会员等级", type:"select", width:140, defaultValue:"-",
									data:()=>{
										return vipLvData;
									},
									props:{ value:'lv', label:'name', children:'children' }
								},
								{ key:"vip_get_time", title:"成为会员", type:"text", width:120,
									formatter: function(val, row, column, index) {
										if (!val) return "-";
										let str = vk.pubfn.timeFormat(val);
										let time1 = val;
										let time2 = Date.now();
										let { todayStart: todayStart1 } = vk.pubfn.getCommonTime(time1);
										let { todayStart: todayStart2 } = vk.pubfn.getCommonTime(time2);
										let time = todayStart2 - todayStart1;
										let day = time / (1000*3600*24) + 1;
										return `${str}（第${Math.floor(day)}天）`;
									}
								},
								{ key:"vip_lv_get_time", title:"当前等级", type:"text", width:120,
									formatter: function(val, row, column, index) {
										if (!val) return "-";
										let str = vk.pubfn.timeFormat(val);
										let time1 = val;
										let time2 = Date.now();
										let { todayStart: todayStart1 } = vk.pubfn.getCommonTime(time1);
										let { todayStart: todayStart2 } = vk.pubfn.getCommonTime(time2);
										let time = todayStart2 - todayStart1;
										let day = time / (1000*3600*24) + 1;
										return `${str}（第${Math.floor(day)}天）`;
									}
								},
							],
						},
						{ key:"tagList", title:"标签", type:"text", width:250,
							formatter: function(val=[], row, column, index) {
								let str = "";
								val.map((item, index) => {
									str += item.name + "、";
								});
								if(str){
									str = str.substring(0,str.length-1);
								}else{
									str = "-";
								}
								return str;
							}
						},
					],
					// 多选框选中的值
					multipleSelection:[],
					// 当前高亮的记录
					selectItem:"",
					rightBtnsMore:[
						{
							title:'更换上级',
							onClick:function(item){
								vk.pubfn.openForm('updateInviter',{ item })
							}
						},
						{
							title:'资产明细',
							onClick:function(item){
								vk.pubfn.openForm('userRecords',{ item })
							}
						},
						{
							title:'标签',
							onClick:function(item){
								vk.pubfn.openForm('userTags',{ item })
							}
						},
						{
							title:'设为客服',
							onClick:function(item){
								vk.pubfn.openForm('isServiceStaff',{ item })
							}
						},
						{
							title:'设为核销员',
							onClick:function(item){
								vk.pubfn.openForm('isVerifyStaff',{ item })
							}
						},
						{
							title:'修改余额',
							onClick:function(item){
								item.type = 1;
								vk.pubfn.openForm('balance',{ item })
							}
						},
						{
							title:'修改积分',
							onClick:function(item){
								item.type = 2;
								vk.pubfn.openForm('integral',{ item })
							}
						},
						{
							title:'余额转账',
							onClick:function(item){
								item.type = 2;
								vk.pubfn.openForm('balanceTransfer',{ item })
							}
						},
						// {
						// 	title:'推广码',
						// 	onClick:function(item){
						// 		item.type = 2;
						// 		that.applyQRcode(item.my_invite_code);
						// 	},
						// 	disabled:function(item){
						// 		return item.fx_lv == 0 || item.is_fx == 0
						// 	}
						// },
					],
					customRightBtns:[
						{
							title: '审核', type: 'success', icon: 'el-icon-edit',
							disabled: function(item){
								return item.fx ? item.fx.status !== 0 : false
							},
							// show:function(item){
							// 	return item.fx.status == 0
							// },
							onClick: function(item){
								vk.pubfn.openForm('examineSalesman',{ item })
							}
						}
					]
				},
				// 表格相关结束 -----------------------------------------------------------
				// 表单相关开始 -----------------------------------------------------------
				// 查询表单请求数据
				queryForm1:{
					// 查询表单数据源，可在此设置默认值
					formData:{
						_id:"",
						is_fx:"",
					},
					// 查询表单的字段规则 fieldName:指定数据库字段名,不填默认等于key
					columns:[
						{ key:"is_fx", title:"用户类型", type:"select", width:140, mode:"=", fieldName:"fx.is_fx",
							clearable: false,
							data:[
								{ value:"", label:"全部" },
								{ value:1, label:"分销员" },
								{ value:0, label:"普通用户" },
								{ value:100, label:"待审核的分销员" }
							]
						},
						{ key:"vip_lv", title:"会员等级", type:"select", width:140, placeholder:"请选择会员等级", mode:"=",
							data:()=>{
								return [{lv:"",name:"全部"},...vipLvData];
							},
							props:{ value:'lv', label:'name', children:'children' }
						},
						{ key:"fx_lv", title:"分销等级", type:"select", width:140, placeholder:"请选择分销等级", mode:"=" ,
							data:()=>{
								return [{lv:"",name:"全部"},...fxLvData];
							},
							fieldName: "fx.lv",
							props:{ value:'lv', label:'name', children:'children' }
						},
						{ key:"status", title:"用户状态", type:"select", width:140, mode:"=",
							data: statusData
						},
						{ key:"nickname", title:"用户昵称", type:"text", width:140, mode:"%%" },
						{ key:"mobile", title:"手机号码", type:"text", width:140, mode:"%%" },
						{ key:"_id", title:"用户ID", type:"text", width:155, mode:"=" },
						{ key:"inviter_uid", title:"所属上级", type:"text", width:140, mode:"=", placeholder:"请输入上级ID", fieldName:"inviter_uid.0" },
						{ key:"comment", title:"用户备注", type:"text", width:140, mode:"%%" },
						{ key:"vip_code", title:"会员编码", type:"text", width:140, mode:"=", fieldName: "vip_code.code" },
						{ key:"is_service_staff", title:"是客服", type:"select", width:100, mode:"=",
							data:[
								{ value:1, label:"是" },
								{ value:0, label:"否" }
							]
						},
						{ key:"is_verify_staff", title:"是扫码人员", type:"select", width:100, mode:"=",
						 data:[
						 		{ value:1, label:"是" },
						 		{ value:0, label:"否" }
						 	]
						},
						{ key:"register_date", title:"注册时间", type:"datetimerange", width:360, mode:"[]" },

					]
				},
				form1:{
					// 表单请求数据，此处可以设置默认值
					data: {

					},
					// 表单属性
					props: {
						// 表单请求地址
						action:"",
						// 表单字段显示规则
						columns:[
							{ key:"nickname", title:"昵称", type:"text" },
							{ key:"mobile", title:"手机号", type:"text" },
							// { key:"vip_lv", title:"会员等级", type:"select", placeholder:"请选择会员等级", clearable: false,
							// 	data:()=>{
							// 		return vipLvData;
							// 	},
							// 	props:{ value:'lv', label:'name', children:'children' }
							// },
							// {
							//   key:"is_fx", title:"分销员", type:"radio",
							//   optionType:"button",
							//   data:[
							//     { value:1, label:"是" },
							//     { value:0, label:"否" }
							//   ]
							// },
							// { key:"fx_lv", title:"分销等级", type:"select", placeholder:"请选择分销等级", clearable: false,
							// 	data:()=>{
							// 		return fxLvData;
							// 	},
							// 	props:{ value:'lv', label:'name', children:'children' }
							// },
							{ key:"comment", title:"备注", type:"text" },
							{ key:"tags", title:"标签", type:"array<string>" },
						],
						// 表单验证规则
						rules:{
							nickname: [
								// 必填
								{ required: true, message: '昵称为必填字段', trigger: 'blur' },
								// 长度在 2-20 个字
								{ min: 2, max: 20, message: '昵称长度在 2 到 20 之间', trigger: 'blur' }
							],
							mobile: [
								// 必须是手机号格式
								{ validator: vk.pubfn.validator("mobile"),  message: '手机号格式错误', trigger: 'blur' }
							],
							comment: [
								{ min: 0, max: 20, message: '备注长度在 0 到 20 之间', trigger: 'blur' }
							]
						},
						// add 代表添加 update 代表修改
						formType:"",
						// 是否显示表单的弹窗
						show:false
					}
				},
				// 其他弹窗表单
				formDatas:{},
				// 表单相关结束 -----------------------------------------------------------
			};
		},
		// 监听 - 页面每次【加载时】执行(如：前进)
		onLoad(options = {}) {
			that = this;
			vk = that.vk;
			that.options = options;
			that.init(options);
		},
		// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
		onReady() {},
		// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
		onShow() {},
		// 监听 - 页面每次【隐藏时】执行(如：返回)
		onHide() {},
		// 函数
		methods: {
			// 页面数据初始化函数
			init(options) {
				originalForms["form1"] = vk.pubfn.copyObject(that.form1);
				originalForms["queryForm1.formData"] = vk.pubfn.copyObject(that.queryForm1.formData);
				if (options._id) that.queryForm1.formData._id = options._id;
				if (options.is_fx){
					that.queryForm1.formData.is_fx = Number(options.is_fx);
					uni.setNavigationBarTitle({
						title:"分销员管理"
					});
				} else {
					uni.setNavigationBarTitle({
						title:"用户管理"
					});
				}
				fxLvData = vk.getVuex("$user.mchInfo.fx.level_rule");
				vipLvData = vk.getVuex("$user.mchInfo.vip_level_rule");
			},
			// 页面跳转
			pageTo(path) {
				vk.navigateTo(path);
			},
			// 表单重置
			resetForm(){
				that.form1 = vk.pubfn.copyObject(originalForms["form1"]);
			},
			// 搜索
			search(){
				that.$refs.table1.search();
			},
			// 刷新
			refresh(){
				that.$refs.table1.refresh();
			},
			// 获取当前选中的行的数据
			getCurrentRow(){
				return that.$refs.table1.getCurrentRow();
			},
			// 监听 - 行的选中高亮事件
			currentChange(val){
				that.table1.selectItem = val;
			},
			// 当选择项发生变化时会触发该事件
			selectionChange(list) {
				that.table1.multipleSelection = list;
			},
			// 查看上级
			querySj(id){
				that.queryForm1.formData = vk.pubfn.copyObject(originalForms["queryForm1.formData"]);
				that.$set(that.queryForm1.formData,"is_fx", "");
				that.$set(that.queryForm1.formData,"_id", id);
				that.search();
			},
			// 查看下级
			queryXj(id){
				that.queryForm1.formData = vk.pubfn.copyObject(originalForms["queryForm1.formData"]);
				that.$set(that.queryForm1.formData,"is_fx", "");
				that.$set(that.queryForm1.formData,"inviter_uid", id);
				that.search();
			},
			// 显示添加页面
			addBtn(){
				that.resetForm();
				that.form1.props.action = 'admin/business/sys/user.add';
				that.form1.props.formType = 'add';
				that.form1.props.title = '添加';
				that.form1.props.show = true;
			},
			// 显示修改页面
			updateBtn({ item }){
				that.form1.props.action = 'admin/business/sys/user.updateBaseInfo';
				that.form1.props.formType = 'update';
				that.form1.props.title = '编辑';
				that.form1.props.show = true;
				that.form1.data = item;
			},
			applyQRcode(inviteCode){
				let h5Config = vk.getVuex('$user.mchInfo.h5') || {};
				let { domain,path } = h5Config;
				let rootPath;
				if (path) {
					rootPath = `${domain}/${path}`;
				} else {
					rootPath = domain;
				}
				let page = "pages/index/index"; // 页面地址
				let url = `${rootPath}/${page}?inviteCode=${inviteCode}`;
				console.log('url: ', url)
				if (that.qrcode && inviteCode == "888888") {
					vk.pubfn.openForm('applyqrcode',{ qrcode: that.qrcode, url })
				} else {
					vk.userCenter.getWeixinMPqrcode({
						title:'生成中...',
					  data: {
					    scene:`1:${inviteCode}`,
					    page
					  },
					  success: (data) =>{
					    // 成功后的逻辑
							if (inviteCode == "888888") {
								that.qrcode = data.base64;
							}
							vk.pubfn.openForm('applyqrcode',{ qrcode: data.base64, url })
					  }
					});
				}
			}
		},
		// 监听属性
		watch: {

		},
		// 计算属性
		computed: {

		}
	};
</script>
<style lang="scss" scoped>
	.page-body {

	}
</style>
